


package jnpf.htgl.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.base.entity.VisualdevEntity;
import jnpf.base.service.IBaseSerialNumberService;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.engine.entity.FlowTaskEntity;
import jnpf.engine.enums.FlowStatusEnum;
import jnpf.exception.DataException;
import jnpf.exception.WorkFlowException;
import jnpf.fico.entity.ZcBillEntity;
import jnpf.fico.entity.ZcBillItemEntity;
import jnpf.fico.service.ZcBillItemService;
import jnpf.fico.service.ZcBillService;
import jnpf.htgl.entity.*;
import jnpf.htgl.mapper.*;
import jnpf.htgl.model.zcglhtglinfo.*;
import jnpf.htgl.service.ZcglHtglInfoService;
import jnpf.htgl.service.ZcglHtglPabService;
import jnpf.permission.entity.UserEntity;
import jnpf.util.GeneraterSwapUtil;
import jnpf.util.JsonUtil;
import jnpf.util.RandomUtil;
import jnpf.util.UserProvider;
import jnpf.zc.entity.ZcglCustomerEntity;
import jnpf.zc.mapper.ZcglCustomerBusinessMapper;
import jnpf.zc.mapper.ZcglCustomerMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.swing.text.html.Option;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 合同管理
 *
 * @版本： V3.2.0
 * @版权： 智果云科技（https://www.jnpfsoft.com）
 * @作者： JNPF开发平台组
 * @日期： 2025-01-12
 */
@Slf4j
@RestController
@Api(tags = "合同管理", value = "example")
@RequestMapping("/api/example/ZcglHtglInfo")
public class ZcglHtglInfoController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;



    @Autowired
    private UserProvider userProvider;

    @Autowired
    private ZcglHtglInfoService zcglHtglInfoService;


    @Autowired
    private ZcglHtglPabService zcglHtglPabService;

    //乙方条款相关
    @Autowired
    private ZcglHtglPabCwtkMapper zcglHtglPabCwtkMapper;
    @Autowired
    private ZcglHtglPabFytkMapper zcglHtglPabFytkMapper;
    @Autowired
    private ZcglHtglPabSpaceMapper zcglHtglPabSpaceMapper;
    @Autowired
    private ZcglHtglQtskzhMapper zcglHtglQtskzhMapper;
    @Autowired
    private ZcglHtglQtydtkMapper zcglHtglQtydtkMapper;
    @Autowired
    private ZcglHtglPabWytkMapper zcglHtglPabWytkMapper;
    @Autowired
    private ZcglHtglPabYjtkMapper zcglHtglPabYjtkMapper;
    @Autowired
    private ZcglHtglSkjhMapper zcglHtglSkjhMapper;
    @Autowired
    private ZcglHtglInfoMapper zcglHtglInfoMapper;
    @Autowired
    private IBaseSerialNumberService iBaseSerialNumberService;
    @Autowired
    private ZcglCustomerMapper zcglCustomerMapper;

    @Autowired
    private ZcBillService zcBillService;
    @Autowired
    private ZcBillItemService zcBillItemService;

    @ApiOperation(value = "合同信息-执行计算任务逻辑", notes = "合同信息-添加")
    @PostMapping(value = "/js")
    public void js() {

        // 构建查询条件
        QueryWrapper<ZcglHtglInfoEntity> queryWrapper = new QueryWrapper<>();
        List<ZcglHtglInfoEntity> list = zcglHtglInfoService.list(queryWrapper);
        for (int h = 0; h < list.size(); h++) {
            ZcglHtglInfoEntity zcglHtglInfoEntity = list.get(h);
            List<ZcBillEntity> zcBillEntities = zcBillService.list(new QueryWrapper<ZcBillEntity>().eq("CONTRACT_NO", zcglHtglInfoEntity.getContractNumber()).orderByAsc("EXPENSE_START_DATE"));
            List<ZcBillItemEntity> allzcBillItemEntities = new ArrayList<>();
            for (int i = 0; i < zcBillEntities.size(); i++) {
                ZcBillEntity zcBillEntity = zcBillEntities.get(i);
                List<ZcBillItemEntity> zcBillItemEntities = zcBillItemService.list(new QueryWrapper<ZcBillItemEntity>().eq("F_ParentId", zcBillEntities.get(i).getId()).eq("status", 1));

                zcBillItemEntities.forEach(o -> {
                    o.setStartTime(zcBillEntity.getExpenseStartDate());
                    o.setEndTime(zcBillEntity.getExpenseEndDate());
                });

                allzcBillItemEntities.addAll(zcBillItemEntities);
            }
            if (zcglHtglInfoEntity.getUserMoney() == null) {
                zcglHtglInfoEntity.setUserMoney(new BigDecimal(0.0));
            }
            //临时保证金
            BigDecimal lsbzj = zcglHtglInfoEntity.getUserMoney();
            ZcBillItemEntity depositItem = allzcBillItemEntities.stream()
                    .filter(item -> "保证金".equals(item.getExpenseItem())) // 假设字段getter为getExpenseItem()
                    .findFirst() // 只取第一条匹配的记录
                    .orElse(null); // 没有匹配时返回null
            List<ZcBillItemEntity> bzjlist = new ArrayList<>();
            bzjlist.add(depositItem);
            System.out.println(allzcBillItemEntities+"操你阿玛");
            //此处处理保证金逻辑    代表首次计算保证金
            if (zcglHtglInfoEntity.getBzj() == null || "".equals(zcglHtglInfoEntity.getBzj()) || zcglHtglInfoEntity.getBzj() != zcglHtglInfoEntity.getEarnestMoney()) {
                for (int i = 0; i < bzjlist.size(); i++) {
                    ZcBillItemEntity receivablesInfo3 = bzjlist.get(i);
                    //假设开始日期在今天之前，说明保证金该给了
                    if (receivablesInfo3.getStartTime().compareTo(new Date()) <= 0) {
                        if (zcglHtglInfoEntity.getUserMoney().compareTo(receivablesInfo3.getRealAmount()) >= 0) {
                            //将这笔收款更改为已经收款了
                            receivablesInfo3.setStatus(2);
                            receivablesInfo3.setPaymentTime(new Date());
//                            receivablesInfo3.setPayType(600);
//                            receivablesInfo3.setRemark(receivablesInfo3.getRemark() + ";系统收费自动支付");
//                            receivablesInfo3.setReceiptDate(new Date());
                            zcBillItemService.updateById(receivablesInfo3);
                            BigDecimal yue = zcglHtglInfoEntity.getUserMoney().subtract(receivablesInfo3.getRealAmount());
                            zcglHtglInfoEntity.setUserMoney(yue);

                            lsbzj = yue;
                            zcglHtglInfoEntity.setBzj(zcglHtglInfoEntity.getEarnestMoney());
                            zcglHtglInfoService.updateById(zcglHtglInfoEntity);
                        } else {
                            BigDecimal bigDecimal = zcglHtglInfoEntity.getEarnestMoney().subtract(zcglHtglInfoEntity.getUserMoney());
                            System.out.println(bigDecimal + "我是多少");
                            //给的钱 不足以给保证金
                            zcglHtglInfoEntity.setBzj(new BigDecimal(0.0).subtract(bigDecimal));
                            zcglHtglInfoService.updateById(zcglHtglInfoEntity);
                            lsbzj = new BigDecimal(0.0);
//                                leaseContractInfo.setUserMoney(new BigDecimal(0.0));

                        }
                    }
                }
            } else if (zcglHtglInfoEntity.getBzj().compareTo(new BigDecimal("0.0")) < 0) {
                //说明给了一部分保证金

            }

//            List<ReceivablesInfo> receivablesInfoList4 = receivablesInfoService.list(new QueryWrapper<ReceivablesInfo>().eq("lease_contract_id", leaseContractInfo.getId()).eq("pay_status", 10).eq("payment_instructions",20).orderByAsc("start_time"));
//            if(receivablesInfoList4.size()==0 || receivablesInfoList4==null){
            for (int i = 0; i < allzcBillItemEntities.size(); i++) {
                ZcBillItemEntity receivablesInfo1 = allzcBillItemEntities.get(i);
                System.out.println("看看日期盘点" + receivablesInfo1.getEndTime().compareTo(new Date()));
                if (receivablesInfo1.getStartTime().compareTo(new Date()) <= 0) {
                    //修改为临时 用户余额
                    if (lsbzj.compareTo(receivablesInfo1.getRealAmount()) >= 0) {
                        //将这笔收款更改为已经收款了
                        receivablesInfo1.setStatus(2);
                        receivablesInfo1.setPaymentTime(new Date());
//                            receivablesInfo1.setPayType(600);
//                            receivablesInfo1.setRemark(receivablesInfo1.getRemark() + ";系统收费自动支付");
//                            receivablesInfo1.setReceiptDate(new Date());
                        zcBillItemService.updateById(receivablesInfo1);
                        zcglHtglInfoEntity.setUserMoney(zcglHtglInfoEntity.getUserMoney().subtract(receivablesInfo1.getRealAmount()));
                        lsbzj = lsbzj.subtract(receivablesInfo1.getRealAmount());
//                        //此时更新合同的余额，继续循环扣除，直到没钱了为止。
                        System.out.println("劳资看你的金钱" + zcglHtglInfoEntity.getUserMoney());
                        zcglHtglInfoService.updateById(zcglHtglInfoEntity);
                    } else {

                    }
                }

            }
//            }

            List<ZcBillItemEntity> allzcBillItemEntitiesDDDD = new ArrayList<>();
            List<ZcBillEntity> zcBillEntities1 = zcBillService.list(new QueryWrapper<ZcBillEntity>().eq("CONTRACT_NO", zcglHtglInfoEntity.getContractNumber()).orderByAsc("EXPENSE_START_DATE"));
            BigDecimal nowYe1 = new BigDecimal(0.0);
            for (int i = 0; i < zcBillEntities1.size(); i++) {
                ZcBillEntity zcBillEntity = zcBillEntities1.get(i);
                List<ZcBillItemEntity> receivablesInfoList11 = zcBillItemService.list(new QueryWrapper<ZcBillItemEntity>().eq("F_ParentId", zcBillEntities.get(i).getId()).eq("status", 1));
                receivablesInfoList11.forEach(o -> {
                    o.setStartTime(zcBillEntity.getExpenseStartDate());
                    o.setEndTime(zcBillEntity.getExpenseEndDate());
                });

                allzcBillItemEntitiesDDDD.addAll(receivablesInfoList11);
                }

                for (int j = 0; j < allzcBillItemEntitiesDDDD.size(); j++) {
                    ZcBillItemEntity receivablesInfo1 = allzcBillItemEntitiesDDDD.get(j);
                    if (receivablesInfo1.getStartTime().before(new Date())) {
                        nowYe1 = nowYe1.add(receivablesInfo1.getRealAmount());
                    }
                }

            zcglHtglInfoEntity.setWaitMoney(nowYe1);
                if (zcglHtglInfoEntity.getBzj().compareTo(new BigDecimal("0.0")) < 0) {
                    zcglHtglInfoEntity.setTotalBalance(lsbzj.subtract(zcglHtglInfoEntity.getWaitMoney()).add(zcglHtglInfoEntity.getBzj()));
                } else {
                    System.out.println(lsbzj + "我是多少嘛");
                    zcglHtglInfoEntity.setTotalBalance(lsbzj.subtract(zcglHtglInfoEntity.getWaitMoney()));
                }


                SimpleDateFormat time1 = new SimpleDateFormat("yyyy-MM-dd");
                System.out.println(zcglHtglInfoEntity.getBzj() + "as1");
                System.out.println(zcglHtglInfoEntity.getEarnestMoney() + "as1211");
                if (zcglHtglInfoEntity.getBzj().compareTo(zcglHtglInfoEntity.getEarnestMoney()) == 0) {
                    zcglHtglInfoEntity.setBzjsm("已交清（" + zcglHtglInfoEntity.getBzj() + ")");
                } else {
                    zcglHtglInfoEntity.setBzjsm("" + zcglHtglInfoEntity.getBzj() + "");
                }
                zcglHtglInfoService.updateById(zcglHtglInfoEntity);

                List<ZcBillEntity> zcBillEntitiesS = zcBillService.list(new QueryWrapper<ZcBillEntity>().eq("CONTRACT_NO", zcglHtglInfoEntity.getContractNumber()).orderByDesc("EXPENSE_END_DATE"));
                List<ZcBillItemEntity> allzcBillItemEntitiesS = new ArrayList<>();
                for (int i1 = 0; i1 < zcBillEntitiesS.size(); i1++) {
                    ZcBillEntity billEntity = zcBillEntitiesS.get(i1);
                    List<ZcBillItemEntity> zcBillItemEntities = zcBillItemService.list(new QueryWrapper<ZcBillItemEntity>().eq("F_ParentId", zcBillEntitiesS.get(i1).getId()).eq("status", 2));
                    zcBillItemEntities.forEach(o -> {
                        o.setStartTime(billEntity.getExpenseStartDate());
                        o.setEndTime(billEntity.getExpenseEndDate());
                    });

                    allzcBillItemEntitiesS.addAll(zcBillItemEntities);
                }
                if (allzcBillItemEntitiesS.size() > 0 && allzcBillItemEntitiesS.get(0).getEndTime() != null) {
                    System.out.println(allzcBillItemEntitiesS.get(0) + "最终的结束时间");
                    zcglHtglInfoEntity.setZjsz(time1.format(allzcBillItemEntitiesS.get(0).getEndTime()));
                    zcglHtglInfoService.updateById(zcglHtglInfoEntity);
                }

                BigDecimal userBalance = zcglHtglInfoEntity.getUserMoney();

                // 筛选RENT_METHOD为"固定租金"的第一条记录
                ZcglHtglPabFytkEntity fixedRentEntity = zcglHtglPabFytkMapper.selectOne(
                        new QueryWrapper<ZcglHtglPabFytkEntity>()
                                .eq("F_ParentId", zcglHtglInfoEntity.getId())
                                .eq("RENT_METHOD", "固定租金") // 添加RENT_METHOD字段筛选
                                .last("limit 1") // 只取第一条记录
                );


                BigDecimal monthlyRent = fixedRentEntity.getMonthlyRent();
                if (userBalance.compareTo(monthlyRent) > 0) {
                    // 计算用户余额可以支付的月数
                    BigDecimal monthsPossible = userBalance.divide(monthlyRent, RoundingMode.DOWN);
                    // 取整数部分
                    int fullMonths = monthsPossible.intValue();
                    System.out.println("用户余额可以支付 " + fullMonths + " 个月的租金。");
                    List<ZcBillEntity> zcBillEntitiesC = zcBillService.list(new QueryWrapper<ZcBillEntity>().eq("CONTRACT_ID", zcglHtglInfoEntity.getId()).orderByAsc("EXPENSE_START_DATE"));
                    List<ZcBillItemEntity> allzcBillItemEntitiesC = new ArrayList<>();
                    for (int iD = 0; iD < zcBillEntitiesC.size(); iD++) {
                        ZcBillEntity zcBillEntity = zcBillEntitiesC.get(iD);
                        List<ZcBillItemEntity> zcBillItemEntities = zcBillItemService.list(new QueryWrapper<ZcBillItemEntity>().eq("F_ParentId", zcBillEntity.getId()).eq("status", 1));

                        zcBillItemEntities.forEach(o -> {
                            o.setStartTime(zcBillEntity.getExpenseStartDate());
                            o.setEndTime(zcBillEntity.getExpenseEndDate());
                        });
                        allzcBillItemEntitiesC.addAll(zcBillItemEntities);


                        //找没给的。时间加上几个月
                        if (!allzcBillItemEntitiesC.isEmpty()) {
                            // 获取第一个条目的 startTime
                            Date startTime = allzcBillItemEntitiesC.get(0).getStartTime();
                            // 将 startTime 加上 fullMonths 个月
                            Date newDate = addMonthsToDate(startTime, fullMonths);
                            // 更新 leaseContractInfo 的 startTime
                            zcglHtglInfoEntity.setZjsz(time1.format(newDate));
                            // 输出更新后的 startTime
                            System.out.println("更新后的 startTime: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(newDate));
                            zcglHtglInfoService.updateById(zcglHtglInfoEntity);
                        }
                    }


                }
        }


    }

    /**
     * 将日期加上指定的月数
     *
     * @param date      原始日期
     * @param months    要加的月数
     * @return          加上月数后的日期
     */
    public static Date addMonthsToDate(Date date, int months) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, months);
        return calendar.getTime();
    }

    /**
     * 列表
     *
     * @param zcglHtglInfoPagination
     * @return
     */
    @ApiOperation("获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody ZcglHtglInfoPagination zcglHtglInfoPagination) throws IOException {
        List<ZcglHtglInfoEntity> list = zcglHtglInfoService.getList(zcglHtglInfoPagination);
        //处理id字段转名称，若无需转或者为空可删除
        List<ZcglHtglInfoListVO> listVO = JsonUtil.getJsonToList(list, ZcglHtglInfoListVO.class);
        for (ZcglHtglInfoListVO zcglHtglInfoVO : listVO) {
            zcglHtglInfoVO.setContractnumber_name(zcglHtglInfoVO.getContractnumber());

            zcglHtglInfoVO.setContracttype_name(generaterSwapUtil.getDicName(zcglHtglInfoVO.getContracttype(), "622532919440706373"));

            zcglHtglInfoVO.setProject_name(generaterSwapUtil.getDicName(zcglHtglInfoVO.getProject(), "622532443626277701"));

            zcglHtglInfoVO.setRelatedcontracts_name(zcglHtglInfoVO.getRelatedcontracts());

            zcglHtglInfoVO.setSigningdate_name(zcglHtglInfoVO.getSigningdate());

            zcglHtglInfoVO.setEffectivedate_name(zcglHtglInfoVO.getEffectivedate());

            zcglHtglInfoVO.setPurposehouse_name(zcglHtglInfoVO.getPurposehouse());

            zcglHtglInfoVO.setContracthandler_name(generaterSwapUtil.userSelectValues(zcglHtglInfoVO.getContracthandler()));

            zcglHtglInfoVO.setIhis_name(generaterSwapUtil.switchSelectValue(zcglHtglInfoVO.getIhis(), "开", "关"));

            zcglHtglInfoVO.setNotes_name(zcglHtglInfoVO.getNotes());

            zcglHtglInfoVO.setPartyname_name(zcglHtglInfoVO.getPartyname());

            zcglHtglInfoVO.setPartybusinesslicense_name(zcglHtglInfoVO.getPartybusinesslicense());

            zcglHtglInfoVO.setPartycontacts_name(zcglHtglInfoVO.getPartycontacts());

            zcglHtglInfoVO.setPartycontactinformation_name(zcglHtglInfoVO.getPartycontactinformation());

            zcglHtglInfoVO.setStarttime_name(zcglHtglInfoVO.getStarttime());

            zcglHtglInfoVO.setEndtime_name(zcglHtglInfoVO.getEndtime());

            zcglHtglInfoVO.setPaymentdeadlinetype_name(generaterSwapUtil.getDicName(zcglHtglInfoVO.getPaymentdeadlinetype(), "622533108956138312"));

            zcglHtglInfoVO.setPaymentdeadline_name(zcglHtglInfoVO.getPaymentdeadline());

            zcglHtglInfoVO.setPaymentdeadlinestatus_name(generaterSwapUtil.getDicName(zcglHtglInfoVO.getPaymentdeadlinestatus(), "622533108956138313"));

            zcglHtglInfoVO.setPaymentzdrq_name(zcglHtglInfoVO.getPaymentzdrq());

            zcglHtglInfoVO.setDescription_name(zcglHtglInfoVO.getDescription());

            zcglHtglInfoVO.setCreatoruserid_name(zcglHtglInfoVO.getCreatoruserid());
            String zcIds = zcglHtglInfoVO.getZcIds();
            if(StrUtil.isNotEmpty(zcIds)){
                List<ZcglHtglPabSpaceVO> zcList = zcglHtglInfoService.getPabSpace(zcIds);
                String result = zcList.stream()
                        .map(ZcglHtglPabSpaceVO::getZcName)  // 获取每个 ZcglHtglPabSpaceVO 的 zcName
                        .collect(Collectors.joining(","));  // 用逗号拼接
                zcglHtglInfoVO.setZcName(result);
            }

            ZcglHtglPabEntity zcglHtglPabEntity = zcglHtglInfoService.getZcglHtglPab(zcglHtglInfoVO.getId());
            if (ObjectUtil.isNotEmpty(zcglHtglPabEntity)) {
                ZcglHtglPabListVO zcglHtglPabListVO = JsonUtil.getJsonToBean(zcglHtglPabEntity, ZcglHtglPabListVO.class);
                zcglHtglPabListVO.setPabcustomername_name(zcglHtglPabListVO.getPabcustomername());

                zcglHtglPabListVO.setPababbreviation_name(zcglHtglPabListVO.getPababbreviation());

                zcglHtglPabListVO.setPabcontacts_name(zcglHtglPabListVO.getPabcontacts());

                zcglHtglPabListVO.setPabcontactnumber_name(zcglHtglPabListVO.getPabcontactnumber());

                zcglHtglPabListVO.setPabidtype_name(zcglHtglPabListVO.getPabidtype());

                zcglHtglPabListVO.setPabidno_name(zcglHtglPabListVO.getPabidno());

                zcglHtglPabListVO.setPabcontactaddress_name(zcglHtglPabListVO.getPabcontactaddress());

                zcglHtglInfoVO.setZcgl_htgl_pab(zcglHtglPabListVO);
            }
            //子表数据转换
        }

        for (ZcglHtglInfoListVO vo : listVO) {
            FlowTaskEntity flowTaskEntity = generaterSwapUtil.getInfoSubmit(vo.getId(), FlowTaskEntity::getStatus);
            if (flowTaskEntity != null) {
                vo.setFlowState(flowTaskEntity.getStatus());
            } else {
                vo.setFlowState(null);
            }
        }
        PageListVO vo = new PageListVO();
        vo.setList(listVO);
        PaginationVO page = JsonUtil.getJsonToBean(zcglHtglInfoPagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);

    }

    /**
     * 创建
     *
     * @param crData
     * @return
     */
    @PostMapping
    @Transactional
    @ApiOperation("创建")
    public ActionResult create(@RequestBody @Validated ZcglHtglInfoFormCheck crData) throws DataException {

        ZcglHtglInfoForm zcglHtglInfoForm = new ZcglHtglInfoForm();
        BeanUtil.copyProperties(crData,zcglHtglInfoForm);
        boolean b = zcglHtglInfoService.checkForm(zcglHtglInfoForm, 0);
        if (b) {
            return ActionResult.fail("单行输入不能重复");
        }
        String visualId = "648163945676284677";
        VisualdevEntity visualdevEntity = generaterSwapUtil.getVisualEntity(visualId);
        String mainId = RandomUtil.uuId();

        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        ZcglHtglInfoEntity entity = JsonUtil.getJsonToBean(zcglHtglInfoForm, ZcglHtglInfoEntity.class);
        entity.setId(mainId);
        //乙方资产经营空间数据
        entity.setZcIds(zcglHtglInfoForm.getZcIds());

        //合同编号验重
        List<ZcglHtglInfoEntity> zcglHtglInfoEntitys = zcglHtglInfoMapper.selectList(new QueryWrapper<ZcglHtglInfoEntity>()
                .eq("CONTRACT_NUMBER", entity.getContractNumber())
        );
        if(IterUtil.isNotEmpty(zcglHtglInfoEntitys)){
            throw new DataException("合同编号已存在");
        }

        //创建合同编号
//        entity.setContractNumber(iBaseSerialNumberService.getSerialNumber("HT",8));

        entity.setCreatortime(DateUtil.date());
        entity.setCreatoruserid(userInfo.getUserId());
        zcglHtglInfoService.save(entity);

        //乙方基础数据
        if (IterUtil.isNotEmpty(zcglHtglInfoForm.getZcgl_htgl_pab())) {
            List<ZcglHtglPabEntity> zcgl_htgl_pabentity = JsonUtil.getJsonToList(zcglHtglInfoForm.getZcgl_htgl_pab(), ZcglHtglPabEntity.class);
            zcgl_htgl_pabentity.stream().forEach(i->{
                //自动生成的字段
                i.setParentid(entity.getId());
                i.setId(mainId);

                String pabCustomerName = i.getPabCustomerName();
                ZcglCustomerEntity zcglCustomerEntity = zcglCustomerMapper.selectById(pabCustomerName);
                if(ObjectUtil.isNotEmpty(zcglCustomerEntity)){
                    i.setPabCustomerName(zcglCustomerEntity.getCustomerName());
                }

                zcglHtglPabService.save(i);
            });

        }

        //乙方费用条款
        if(IterUtil.isNotEmpty(zcglHtglInfoForm.getZcgl_htgl_pab_fytks())){
            List<ZcglHtglPabFytkEntity> zcgl_htgl_pab_fytks = zcglHtglInfoForm.getZcgl_htgl_pab_fytks();
            System.out.println(zcgl_htgl_pab_fytks.get(0).getAdvancePaymentDays()+"aasas1");
            zcgl_htgl_pab_fytks.stream().forEach(i->{
                i.setParentid(entity.getId());
                zcglHtglPabFytkMapper.insert(i);
            });
            //此处更新保证金都主表上面  ，防止第一个是物业，所以在此处进行傻瓜式判断。经过调研，一般就是1个租金和1个物业
            if(zcgl_htgl_pab_fytks.get(0).getRentMethod().equals("固定租金")){
                entity.setEarnestMoney(zcgl_htgl_pab_fytks.get(0).getEarnestMoney());

            }
            if(zcgl_htgl_pab_fytks.size()>2){
                if(zcgl_htgl_pab_fytks.get(1).getRentMethod().equals("固定租金")){
                    entity.setEarnestMoney(zcgl_htgl_pab_fytks.get(1).getEarnestMoney());
                }
            }

        }
        //此处更新保证金都主表上面
        zcglHtglInfoService.saveOrUpdate(entity);

        //乙方押金条款
        if(ObjectUtil.isNotEmpty(zcglHtglInfoForm.getZcgl_htgl_pab_yjtk())){
            ZcglHtglPabYjtkEntity zcgl_htgl_pab_yjtk = zcglHtglInfoForm.getZcgl_htgl_pab_yjtk();
            zcgl_htgl_pab_yjtk.setParentid(entity.getId());
            zcglHtglPabYjtkMapper.insert(zcgl_htgl_pab_yjtk);
        }
        //乙方车位条款
        if(ObjectUtil.isNotEmpty(zcglHtglInfoForm.getZcgl_htgl_pab_cwtk())){
            ZcglHtglPabCwtkEntity zcgl_htgl_pab_cwtk = zcglHtglInfoForm.getZcgl_htgl_pab_cwtk();
            zcgl_htgl_pab_cwtk.setParentid(entity.getId());
            zcglHtglPabCwtkMapper.insert(zcgl_htgl_pab_cwtk);
        }
        //乙方违约条款
        if(ObjectUtil.isNotEmpty(zcglHtglInfoForm.getZcgl_htgl_pab_wytk())){
            ZcglHtglPabWytkEntity zcgl_htgl_pab_wytk = zcglHtglInfoForm.getZcgl_htgl_pab_wytk();
            zcgl_htgl_pab_wytk.setParentid(entity.getId());
            zcglHtglPabWytkMapper.insert(zcgl_htgl_pab_wytk);
        }
        //乙方收款计划
        List<NewZcglHtjhSkjhVO.SkjhEntity> zcgl_htgl_skjh = zcglHtglInfoForm.getZcgl_htgl_skjhs();
        if(IterUtil.isNotEmpty(zcgl_htgl_skjh)){
            zcgl_htgl_skjh.stream().forEach(zc->{
                List<ZcglHtjhSkjhVO> listSk = zc.getListSk();
                if(IterUtil.isNotEmpty(listSk)){
                    listSk.stream().forEach(i->{
                        ZcglHtglSkjhEntity zcglHtglSkjhEntity = new ZcglHtglSkjhEntity(i,zc.getRelatedSpace());
                        zcglHtglSkjhEntity.setParentid(entity.getId());
                        zcglHtglSkjhEntity.setCreatortime(new Date());
                        zcglHtglSkjhEntity.setCreatoruserid(userInfo.getUserAccount());
                        zcglHtglSkjhMapper.insert(zcglHtglSkjhEntity);
                    });
                }
            });

        }

        //其他收款账户
        if(IterUtil.isNotEmpty(zcglHtglInfoForm.getZcgl_htgl_qtskzhs())){
            List<ZcglHtglQtskzhEntity> zcgl_htgl_qtskzhs = zcglHtglInfoForm.getZcgl_htgl_qtskzhs();
            zcgl_htgl_qtskzhs.stream().forEach(i->{
                i.setParentid(entity.getId());
                zcglHtglQtskzhMapper.insert(i);
            });
        }

        //其他约定条款
        if(IterUtil.isNotEmpty(zcglHtglInfoForm.getZcgl_htgl_qtydtks())){
            List<ZcglHtglQtydtkEntity> zcgl_htgl_qtydtks = zcglHtglInfoForm.getZcgl_htgl_qtydtks();
            zcgl_htgl_qtydtks.stream().forEach(i->{
                i.setParentid(entity.getId());
                zcglHtglQtydtkMapper.insert(i);
            });
        }

        if (FlowStatusEnum.submit.getMessage().equals(zcglHtglInfoForm.getStatus())) {
            try {
                visualdevEntity.setFullName(crData.getTitle());
                generaterSwapUtil.submitFlowTask(visualdevEntity, mainId, zcglHtglInfoForm, userInfo, zcglHtglInfoForm.getCandidateList(), zcglHtglInfoForm.getFlowUrgent());
            } catch (WorkFlowException e) {
                e.printStackTrace();
            }
            return ActionResult.success("提交成功，请耐心等待");
        }
        return ActionResult.success("保存成功");
    }


    /**
     * 信息
     *
     * @param id
     * @return
     */
    @ApiOperation("信息")
    @GetMapping("/{id}")
    public ActionResult<ZcglHtglInfoInfoVO> info(@PathVariable("id") String id) {
        ZcglHtglInfoEntity entity = zcglHtglInfoService.getInfo(id);
        ZcglHtglInfoInfoVO vo = JsonUtil.getJsonToBean(entity, ZcglHtglInfoInfoVO.class);
        //子表
        //乙方信息
        QueryWrapper<ZcglHtglPabEntity> queryWrapperZcglHtglPab = new QueryWrapper<>();
        queryWrapperZcglHtglPab.lambda().eq(ZcglHtglPabEntity::getParentid, entity.getId());
        List<ZcglHtglPabEntity> zcgl_htgl_pabEntity = zcglHtglPabService.list(queryWrapperZcglHtglPab);
        List<ZcglHtglPabModel> zcglHtglPabModel = JsonUtil.getJsonToList(zcgl_htgl_pabEntity, ZcglHtglPabModel.class);
        vo.setZcgl_htgl_pab(zcglHtglPabModel);
        //乙方车位条款
        ZcglHtglPabCwtkEntity zcglHtglPabCwtkEntity = zcglHtglPabCwtkMapper.selectOne(new QueryWrapper<ZcglHtglPabCwtkEntity>()
                .eq("F_PARENTID", entity.getId())
        );
        vo.setZcgl_htgl_pab_cwtk(zcglHtglPabCwtkEntity);
        //乙方费用条款
        List<ZcglHtglPabFytkEntity> zcglHtglPabFytkEntitys = zcglHtglPabFytkMapper.selectList(new QueryWrapper<ZcglHtglPabFytkEntity>()
                .eq("F_PARENTID", entity.getId())
        );
        vo.setZcgl_htgl_pab_fytks(zcglHtglPabFytkEntitys);

        //乙方经营空间
        List<ZcglHtglPabSpaceVO> list = zcglHtglInfoService.getPabSpace(entity.getZcIds());
        vo.setZcgl_htgl_pab_spaces(list);

        //将资产详细地址单独拿出来返给前端
        if(IterUtil.isNotEmpty(list)){
            String address = list.stream()
                    .map(ZcglHtglPabSpaceVO::getAddress)
                    .collect(Collectors.joining(","));
            vo.setAddress(address);
        }

        //乙方违约条款
        ZcglHtglPabWytkEntity zcglHtglPabWytkEntity = zcglHtglPabWytkMapper.selectOne(new QueryWrapper<ZcglHtglPabWytkEntity>()
                .eq("F_PARENTID", entity.getId())
        );
        vo.setZcgl_htgl_pab_wytk(zcglHtglPabWytkEntity);
        //乙方押金条款
        ZcglHtglPabYjtkEntity zcglHtglPabYjtkEntity = zcglHtglPabYjtkMapper.selectOne(new QueryWrapper<ZcglHtglPabYjtkEntity>()
                .eq("F_PARENTID", entity.getId())
        );
        vo.setZcgl_htgl_pab_yjtk(zcglHtglPabYjtkEntity);
        //其他收款账户
        List<ZcglHtglQtskzhEntity> htglQtskzhEntityList = zcglHtglQtskzhMapper.selectList(new QueryWrapper<ZcglHtglQtskzhEntity>()
                .eq("F_PARENTID", entity.getId())
        );
        vo.setZcgl_htgl_qtskzhs(htglQtskzhEntityList);
        //其他约定条款
        List<ZcglHtglQtydtkEntity> qtydtkEntityList = zcglHtglQtydtkMapper.selectList(new QueryWrapper<ZcglHtglQtydtkEntity>()
                .eq("F_PARENTID", entity.getId())
        );
        vo.setZcgl_htgl_qtydtks(qtydtkEntityList);
        //收款计划
        List<ZcglHtglSkjhEntity> zcglHtglSkjhList = zcglHtglSkjhMapper.getSkjhs(entity.getId());
        if(IterUtil.isNotEmpty(zcglHtglSkjhList)){
            Map<String, List<ZcglHtglSkjhEntity>> groupedBySpace = zcglHtglSkjhList.stream()
                    .collect(Collectors.groupingBy(ZcglHtglSkjhEntity::getRelatedSpace));
            List<NewZcglHtjhSkjhVO.SkjhEntity> lskjh = new ArrayList<>();
            for (Map.Entry<String, List<ZcglHtglSkjhEntity>> entry : groupedBySpace.entrySet()) {
                NewZcglHtjhSkjhVO.SkjhEntity skjhEntity = new NewZcglHtjhSkjhVO.SkjhEntity();
                //根据关联空间id查询出关联空间名称
                List<ZcglHtglPabSpaceVO> pabSpace = zcglHtglInfoService.getPabSpace(entry.getKey());
                String result = pabSpace.stream()
                        .map(ZcglHtglPabSpaceVO::getZcName)
                        .collect(Collectors.joining(","));
                skjhEntity.setRelatedSpace(result);
                //子表也要替换为中文
                entry.getValue().forEach(o -> {
                    o.setRelatedSpace(result);
                });
                List<ZcglHtglSkjhEntity> value = entry.getValue();
                List<ZcglHtjhSkjhVO> jsonToList = JsonUtil.getJsonToList(value, ZcglHtjhSkjhVO.class);
                skjhEntity.setListSk(jsonToList);
                lskjh.add(skjhEntity);
            }
            vo.setSkjhEntitys(lskjh);
        }
            FlowTaskEntity flowTaskEntity = generaterSwapUtil.getInfoSubmit(vo.getId(), FlowTaskEntity::getStatus);
            if (flowTaskEntity != null) {
                vo.setFlowState(flowTaskEntity.getStatus());
            } else {
                vo.setFlowState(null);
            }

        return ActionResult.success(vo);
    }


    /**
     * 更新
     *
     * @param id
     * @param upData
     * @return
     */
    @PutMapping("/{id}")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("更新")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid Map<String, Object> upData) throws DataException, JsonProcessingException {
        // 解析主表单数据
        ZcglHtglInfoForm zcglHtglInfoForm = JsonUtil.getJsonToBean(upData, ZcglHtglInfoForm.class);
        String zcgl_htgl_skjh = JSONUtil.toJsonStr(upData.get("zcgl_htgl_skjh"));
        List<NewZcglHtjhSkjhVO.SkjhEntity> skjhEntity = JSONUtil.toList(zcgl_htgl_skjh, NewZcglHtjhSkjhVO.SkjhEntity.class);
        zcglHtglInfoForm.setZcgl_htgl_skjhs(skjhEntity);

        // 修复：正确转换子列表数据类型（不使用getObjectToJson）
        Object fytkData = upData.get("zcgl_htgl_pab_fytk");
        if (fytkData != null) {
            // 先将对象转为JSON字符串（使用Jackson的默认方法）
            String fytkJson = new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(fytkData);
            // 再将JSON字符串转为目标类型列表
            List<ZcglHtglPabFytkEntity> fytkList = JsonUtil.getJsonToList(fytkJson, ZcglHtglPabFytkEntity.class);
            zcglHtglInfoForm.setZcgl_htgl_pab_fytks(fytkList);
        }

        System.out.println("查看参数" + zcglHtglInfoForm);

        // 表单校验
        boolean b = zcglHtglInfoService.checkForm(zcglHtglInfoForm, 1);
        if (b) {
            return ActionResult.fail("单行输入不能重复");
        }

        String visualId = "648163945676284677";
        VisualdevEntity visualdevEntity = generaterSwapUtil.getVisualEntity(visualId);
        UserInfo userInfo = userProvider.get();
        ZcglHtglInfoEntity entity = zcglHtglInfoService.getInfo(id);

        if (entity != null) {
            // 转换主实体并更新
            ZcglHtglInfoEntity subentity = JsonUtil.getJsonToBean(zcglHtglInfoForm, ZcglHtglInfoEntity.class);
            boolean b1 = zcglHtglInfoService.updateById(subentity);
            if (!b1) {
                return ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
            }

            // 处理子表数据：ZcglHtglPabEntity
            List<ZcglHtglPabModel> zcgl_htgl_pab = zcglHtglInfoForm.getZcgl_htgl_pab();
            if (IterUtil.isNotEmpty(zcgl_htgl_pab)) {
                List<ZcglHtglPabEntity> zcgl_htgl_pabentity = JsonUtil.getJsonToList(
                        new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(zcgl_htgl_pab),
                        ZcglHtglPabEntity.class
                );
                if (IterUtil.isNotEmpty(zcgl_htgl_pabentity)) {
                    zcgl_htgl_pabentity.stream().forEach(i -> {
                        i.setParentid(entity.getId());
                        zcglHtglPabService.updateById(i);
                    });
                }
            }

            // 处理子表数据：ZcglHtglPabFytkEntity
            List<ZcglHtglPabFytkEntity> zcgl_htgl_pab_fytks = zcglHtglInfoForm.getZcgl_htgl_pab_fytks();
            System.out.println("子表数据：" + zcgl_htgl_pab_fytks);
            if (IterUtil.isNotEmpty(zcgl_htgl_pab_fytks)) {
                zcgl_htgl_pab_fytks.stream().forEach(i -> {
                    i.setParentid(entity.getId());
                    zcglHtglPabFytkMapper.updateById(i);
                });
            }

            // 处理子表数据：ZcglHtglPabSpaceEntity
            List<ZcglHtglPabSpaceEntity> zcgl_htgl_pab_space = zcglHtglInfoForm.getZcgl_htgl_pab_space();
            if (IterUtil.isNotEmpty(zcgl_htgl_pab_space)) {
                zcgl_htgl_pab_space.stream().forEach(i -> {
                    i.setParentid(entity.getId());
                    zcglHtglPabSpaceMapper.updateById(i);
                });
            }

            // 处理子表数据：ZcglHtglQtskzhEntity
            List<ZcglHtglQtskzhEntity> zcgl_htgl_qtskzhs = zcglHtglInfoForm.getZcgl_htgl_qtskzhs();
            if (IterUtil.isNotEmpty(zcgl_htgl_qtskzhs)) {
                zcgl_htgl_qtskzhs.stream().forEach(i -> {
                    i.setParentid(entity.getId());
                    zcglHtglQtskzhMapper.updateById(i);
                });
            }

            // 处理子表数据：ZcglHtglQtydtkEntity
            List<ZcglHtglQtydtkEntity> zcgl_htgl_qtydtks = zcglHtglInfoForm.getZcgl_htgl_qtydtks();
            if (IterUtil.isNotEmpty(zcgl_htgl_qtydtks)) {
                zcgl_htgl_qtydtks.stream().forEach(i -> {
                    i.setParentid(entity.getId());
                    zcglHtglQtydtkMapper.updateById(i);
                });
            }
            // 处理子表数据：ZcglHtglSkjhEntity
            List<NewZcglHtjhSkjhVO.SkjhEntity> zcgl_htgl_skjhs = zcglHtglInfoForm.getZcgl_htgl_skjhs();
            if (IterUtil.isNotEmpty(zcgl_htgl_skjhs)) {
                zcgl_htgl_skjhs.stream().forEach(i->{
                    List<ZcglHtjhSkjhVO> listSk = i.getListSk();
                    if(IterUtil.isNotEmpty(listSk)){
                        zcglHtglSkjhMapper.deleteByFid(listSk.get(0).getParentid());
                        zcglHtglSkjhMapper.deleteHyByFid(listSk.get(0).getParentid());
                        listSk.stream().forEach(k->{
                            ZcglHtglSkjhEntity zcglHtglSkjhEntity = new ZcglHtglSkjhEntity();
                            BeanUtil.copyProperties(k,zcglHtglSkjhEntity);
                            zcglHtglSkjhEntity.setParentid(entity.getId());
                            zcglHtglSkjhMapper.insert(zcglHtglSkjhEntity);
                        });
                    }
                });
            }

            // 处理流程提交

            if (FlowStatusEnum.submit.getMessage().equals(zcglHtglInfoForm.getStatus())) {
                try {
                    if (upData.get("title") != null) {
                        visualdevEntity.setFullName(upData.get("title").toString());
                    }
                    generaterSwapUtil.submitFlowTask(visualdevEntity, id, subentity, userInfo,
                            zcglHtglInfoForm.getCandidateList(), zcglHtglInfoForm.getFlowUrgent());
                } catch (WorkFlowException e) {
                    e.printStackTrace();
                }
                return ActionResult.success("提交成功，请耐心等待");
            }

            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation("删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        ZcglHtglInfoEntity entity = zcglHtglInfoService.getInfo(id);
        if (entity != null) {
            FlowTaskEntity taskEntity = generaterSwapUtil.getInfoSubmit(id, FlowTaskEntity::getId, FlowTaskEntity::getStatus);
            if (taskEntity != null) {
                try {
                    generaterSwapUtil.deleteFlowTask(taskEntity);
                } catch (WorkFlowException e) {
                    e.printStackTrace();
                }
            }
            zcglHtglInfoService.delete(entity);
            //子表数据
            QueryWrapper<ZcglHtglPabEntity> queryWrapperZcglHtglPab = new QueryWrapper<>();
            queryWrapperZcglHtglPab.lambda().eq(ZcglHtglPabEntity::getParentid, entity.getId());
            zcglHtglPabService.remove(queryWrapperZcglHtglPab);

        }
        return ActionResult.success("删除成功");
    }


    @PostMapping(value = "/createSkjh")
    @Transactional
    @ApiOperation("生成收款计划")
    public ActionResult createSkjh(@RequestBody ZcglHtglInfoForm zcglHtglInfoForm) {
        return zcglHtglInfoService.createSkjh(zcglHtglInfoForm);
    }

    @ApiOperation("合同管理基础数据变更")
    @PostMapping("/htglInfo/change")
    public ActionResult<?> htglInfoChange(@RequestBody ZcglHtglInfoChangeEntity entity) {
        zcglHtglInfoService.htglInfoChange(entity);
        return ActionResult.success();
    }


}
